﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using RebellionII.GameObjects.Map;
using RebEngine.GameComponents;
using RebEngine.Managers;
using RebEngine.Models;
using RebEngine.SceneObject;
using RebellionII.GUI;
using RebEngine.SceneObject.SceneGraph;
using TomShane.Neoforce.Controls;
using RebellionII.GameObjects.Units.Instances;
using RebEngine.Interfaces;
using RebellionII.GameObjects;
using RebellionII.GameObjects.Units;
using RebellionII.GameObjects.Other;


namespace RebellionII.GameScreens
{
    public class GameplayScreen: GameScreen
    {
        private bool isHost;

        List<VertexPositionColor> pointList = new List<VertexPositionColor>();
        List<short> lineListIndicies = new List<short>();
        BasicEffect basicEffect;
        private static float delta;
        MouseState currentState;
        int currentZ = 0;

        ImageBox popularSupport, fleetIcon, missionIcon, resourceIcon, manufactureIcon, defenceIcon, conflictIcon, chatIcon;
        ImageBox planetOverviewIcon, mapOverviewIcon, fleetOverviewIcon, characterOverviewIcon;

        public GameplayScreen(bool isServer)
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.0f);
            TransitionOffTime = TimeSpan.FromSeconds(1.0f);
            isHost = isServer;
            
            InputManager.Manager.Input.KeyPress += new TomShane.Neoforce.Controls.KeyEventHandler(HandleInput);
            InputManager.Manager.Input.MouseDown += new TomShane.Neoforce.Controls.MouseEventHandler(HandleMouseInput);

            currentState = new MouseState();

            Camera newCamera = new Camera();
            NetClientManager.YourTeam = TeamName.Alliance;
            
            newCamera.NearPlane = 1.0f;
            newCamera.FarPlane = 10000.0f;
            newCamera.Position = new Vector3(450, -350, 280);

            newCamera.Reference = new Vector3(0, 0, -100);
           
            CameraManager.AddCamera(newCamera, CameraManager.CameraNumber._default);
            CameraManager.SetActiveCamera(CameraManager.CameraNumber._default);

            Initialize();
        }

            
            


        /// <summary>
        /// Loads in all the planets and their neighbors to display the lines. Also adds in the GUI for Overview and Messages
        /// </summary>
        public override void Initialize()
        {
            basicEffect = new BasicEffect(EngineManager.Device);
            basicEffect.VertexColorEnabled = true;

            foreach (KeyValuePair<int, RebSystem> temp in NetClientManager.gameUniverse.dUniverse)
            {
                pointList.Add(new VertexPositionColor(new Vector3(temp.Value.vPosition.X, temp.Value.vPosition.Y, -1.0f), new Color(new Vector4(Color.GhostWhite.ToVector3(), 100))));
            }

            foreach (KeyValuePair<int, RebSystem> temp in NetClientManager.gameUniverse.dUniverse)
            {
                short thisIndex = (short)pointList.IndexOf((new VertexPositionColor(new Vector3(temp.Value.vPosition.X, temp.Value.vPosition.Y, -1.0f), new Color(new Vector4(Color.GhostWhite.ToVector3(), 100)))));
                foreach (int dest in temp.Value.lNeighbours)
                {
                    short index = (short)pointList.IndexOf(new VertexPositionColor(new Vector3(NetClientManager.gameUniverse.dUniverse[dest].vPosition.X,
                        NetClientManager.gameUniverse.dUniverse[dest].vPosition.Y, -1.0f),new Color(new Vector4(Color.GhostWhite.ToVector3(), 100))));
                    lineListIndicies.Add(thisIndex);
                    lineListIndicies.Add(index);
                }
            }

            #region Input Variables
            planetOverviewIcon = new ImageBox(InputManager.Manager);
            planetOverviewIcon.Init();
            planetOverviewIcon.Left = (int)(0.2 * EngineManager.Width);
            planetOverviewIcon.Width = (int)(0.025 * EngineManager.Width);
            planetOverviewIcon.Top = (int)(0.03 * EngineManager.Height);
            planetOverviewIcon.Height = (int)(0.035 * EngineManager.Height);
            planetOverviewIcon.SizeMode = SizeMode.Stretched;
            planetOverviewIcon.Image = TextureManager.GetTexture("f1img").BaseTexture as Texture2D;
            InputManager.Manager.Add(planetOverviewIcon);

            mapOverviewIcon = new ImageBox(InputManager.Manager);
            mapOverviewIcon.Init();
            mapOverviewIcon.Left = (int)(0.25 * EngineManager.Width);
            mapOverviewIcon.Width = (int)(0.025 * EngineManager.Width);
            mapOverviewIcon.Top = (int)(0.03 * EngineManager.Height);
            mapOverviewIcon.Height = (int)(0.035 * EngineManager.Height);
            mapOverviewIcon.SizeMode = SizeMode.Stretched;
            mapOverviewIcon.Image = TextureManager.GetTexture("f2img").BaseTexture as Texture2D;
            InputManager.Manager.Add(mapOverviewIcon);

            fleetOverviewIcon = new ImageBox(InputManager.Manager);
            fleetOverviewIcon.Init();
            fleetOverviewIcon.Left = (int)(0.3 * EngineManager.Width);
            fleetOverviewIcon.Width = (int)(0.025 * EngineManager.Width);
            fleetOverviewIcon.Top = (int)(0.03 * EngineManager.Height);
            fleetOverviewIcon.Height = (int)(0.035 * EngineManager.Height);
            fleetOverviewIcon.SizeMode = SizeMode.Stretched;
            fleetOverviewIcon.Image = TextureManager.GetTexture("f3img").BaseTexture as Texture2D;
            InputManager.Manager.Add(fleetOverviewIcon);

            characterOverviewIcon = new ImageBox(InputManager.Manager);
            characterOverviewIcon.Init();
            characterOverviewIcon.Left = (int)(0.35 * EngineManager.Width);
            characterOverviewIcon.Width = (int)(0.025 * EngineManager.Width);
            characterOverviewIcon.Top = (int)(0.03 * EngineManager.Height);
            characterOverviewIcon.Height = (int)(0.035 * EngineManager.Height);
            characterOverviewIcon.SizeMode = SizeMode.Stretched;
            characterOverviewIcon.Image = TextureManager.GetTexture("f4img").BaseTexture as Texture2D;
            InputManager.Manager.Add(characterOverviewIcon);


            popularSupport = new ImageBox(InputManager.Manager);
            popularSupport.Init();
            popularSupport.Left = (int)(0.9613 * EngineManager.Width);
            popularSupport.Width = (int)(0.0252 * EngineManager.Width);
            popularSupport.Top = (int)(0.279 * EngineManager.Height);
            popularSupport.Height = (int)(0.04 * EngineManager.Height);
            popularSupport.SizeMode = SizeMode.Stretched;
            popularSupport.Image = TextureManager.GetTexture("PopularSupport").BaseTexture as Texture2D;
            popularSupport.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(popularSupport);

            fleetIcon = new ImageBox(InputManager.Manager);
            fleetIcon.Init();
            fleetIcon.Left = (int)(0.9613 * EngineManager.Width);
            fleetIcon.Width = (int)(0.0252 * EngineManager.Width);
            fleetIcon.Top = (int)(0.335 * EngineManager.Height);
            fleetIcon.Height = (int)(0.04 * EngineManager.Height);
            fleetIcon.SizeMode = SizeMode.Stretched;
            fleetIcon.Image = TextureManager.GetTexture("FleetIcon").BaseTexture as Texture2D;
            fleetIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(fleetIcon);

            missionIcon = new ImageBox(InputManager.Manager);
            missionIcon.Init();
            missionIcon.Left = (int)(0.9613 * EngineManager.Width);
            missionIcon.Width = (int)(0.0252 * EngineManager.Width);
            missionIcon.Top = (int)(0.39 * EngineManager.Height);
            missionIcon.Height = (int)(0.04 * EngineManager.Height);
            missionIcon.SizeMode = SizeMode.Stretched;
            missionIcon.Image = TextureManager.GetTexture("MissionIcon").BaseTexture as Texture2D;
            missionIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(missionIcon);

            resourceIcon = new ImageBox(InputManager.Manager);
            resourceIcon.Init();
            resourceIcon.Left = (int)(0.9613 * EngineManager.Width);
            resourceIcon.Width = (int)(0.0252 * EngineManager.Width);
            resourceIcon.Top = (int)(0.445 * EngineManager.Height);
            resourceIcon.Height = (int)(0.04 * EngineManager.Height);
            resourceIcon.SizeMode = SizeMode.Stretched;
            resourceIcon.Image = TextureManager.GetTexture("ResourceIcon").BaseTexture as Texture2D;
            resourceIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(resourceIcon);

            manufactureIcon = new ImageBox(InputManager.Manager);
            manufactureIcon.Init();
            manufactureIcon.Left = (int)(0.9613 * EngineManager.Width);
            manufactureIcon.Width = (int)(0.0252 * EngineManager.Width);
            manufactureIcon.Top = (int)(0.5 * EngineManager.Height);
            manufactureIcon.Height = (int)(0.04 * EngineManager.Height);
            manufactureIcon.SizeMode = SizeMode.Stretched;
            manufactureIcon.Image = TextureManager.GetTexture("ManufactureIcon").BaseTexture as Texture2D;
            manufactureIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(manufactureIcon);

            defenceIcon = new ImageBox(InputManager.Manager);
            defenceIcon.Init();
            defenceIcon.Left = (int)(0.9613 * EngineManager.Width);
            defenceIcon.Width = (int)(0.0252 * EngineManager.Width);
            defenceIcon.Top = (int)(0.5555 * EngineManager.Height);
            defenceIcon.Height = (int)(0.04 * EngineManager.Height);
            defenceIcon.SizeMode = SizeMode.Stretched;
            defenceIcon.Image = TextureManager.GetTexture("DefenceIcon").BaseTexture as Texture2D;
            defenceIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(defenceIcon);

            conflictIcon = new ImageBox(InputManager.Manager);
            conflictIcon.Init();
            conflictIcon.Left = (int)(0.9613 * EngineManager.Width);
            conflictIcon.Width = (int)(0.0252 * EngineManager.Width);
            conflictIcon.Top = (int)(0.611 * EngineManager.Height);
            conflictIcon.Height = (int)(0.04 * EngineManager.Height);
            conflictIcon.SizeMode = SizeMode.Stretched;
            conflictIcon.Image = TextureManager.GetTexture("ConflictIcon").BaseTexture as Texture2D;
            conflictIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(conflictIcon);

            chatIcon = new ImageBox(InputManager.Manager);
            chatIcon.Init();
            chatIcon.Left = (int)(0.9613 * EngineManager.Width);
            chatIcon.Width = (int)(0.0252 * EngineManager.Width);
            chatIcon.Top = (int)(0.6658 * EngineManager.Height);
            chatIcon.Height = (int)(0.04 * EngineManager.Height);
            chatIcon.SizeMode = SizeMode.Stretched;
            chatIcon.Image = TextureManager.GetTexture("Chat").BaseTexture as Texture2D;
            chatIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            InputManager.Manager.Add(chatIcon);
#endregion
        }

        /// <summary>
        /// Creates the objects to show planets from NetClientManagers GameUniverse. Also adds the icons to each planet
        /// </summary>
        public override void LoadContent()
        {
            base.LoadContent();

            foreach (var temp in NetClientManager.gameUniverse.dUniverse)
            {
                RebSceneObject systemObject = new RebSceneObject(temp.Value.sName, new Material("basicEffect", 0), temp.Key);
                systemObject.Position = new Vector3(temp.Value.vPosition.X, temp.Value.vPosition.Y, 0.0f); ;
                systemObject.ModelName = "octasphere";
                systemObject.ReadyToRender = true;
                systemObject.Scale = new Vector3(3.5f, 3.7f, 3.5f);
                systemObject.Material.TextureList.Add("planet_temperate");
                systemObject.UpdateBoundingBox();
                SceneObjectNode systemNode = new SceneObjectNode(systemObject, temp.Value.sName);

                RebSceneObject buildIcon = new RebSceneObject("MainBuild", new Material("basicEffect", 0), temp.Key);
                buildIcon.Position = new Vector3(temp.Value.vPosition.X - 5, temp.Value.vPosition.Y - 5, 0.0f);
                buildIcon.ModelName = "buildIcon";
                buildIcon.ReadyToRender = true;
                buildIcon.Scale = new Vector3(0.5f, 0.5f, 0.5f);
                buildIcon.UpdateBoundingBox();
                SceneObjectNode build = new SceneObjectNode(buildIcon, "MainBuild");

                RebSceneObject missionIcon = new RebSceneObject("Mission", new Material("basicEffect", 0), temp.Key);
                missionIcon.Position = new Vector3(temp.Value.vPosition.X + 5, temp.Value.vPosition.Y - 5, 0.0f);
                missionIcon.ModelName = "missionIcon";
                missionIcon.ReadyToRender = true;
                missionIcon.Scale = new Vector3(0.3f, 0.3f, 0.3f);
                missionIcon.UpdateBoundingBox();
                SceneObjectNode mission = new SceneObjectNode(missionIcon, "Mission");

                RebSceneObject shipIcon = new RebSceneObject("ShipBuild", new Material("basicEffect", 0), temp.Key);
                shipIcon.Position = new Vector3(temp.Value.vPosition.X + 1, temp.Value.vPosition.Y + 6, 0.0f);
                shipIcon.ModelName = "shipIcon";
                shipIcon.ReadyToRender = true;
                shipIcon.Scale = new Vector3(0.3f, 0.3f, 0.3f);
                shipIcon.UpdateBoundingBox();
                SceneObjectNode ship = new SceneObjectNode(shipIcon, "ShipBuild");


                RebSceneObject facIcon = new RebSceneObject("FacBuild", new Material("basicEffect", 0), temp.Key);
                facIcon.Position = new Vector3(temp.Value.vPosition.X + 6, temp.Value.vPosition.Y + 1, 0.0f); 
                facIcon.ModelName = "facIcon";
                facIcon.ReadyToRender = true;
                facIcon.Scale = new Vector3(0.3f, 0.3f, 0.3f);
                facIcon.UpdateBoundingBox();
                SceneObjectNode fac = new SceneObjectNode(facIcon, "FacBuild");

                RebSceneObject troopIcon = new RebSceneObject("TroopBuild", new Material("basicEffect", 0), temp.Key);
                troopIcon.Position = new Vector3(temp.Value.vPosition.X + 4.5f, temp.Value.vPosition.Y + 4.5f, 0.0f); 
                troopIcon.ModelName = "troopIcon";
                troopIcon.ReadyToRender = true;
                troopIcon.Scale = new Vector3(0.3f, 0.3f, 0.3f);
                troopIcon.UpdateBoundingBox();
                SceneObjectNode troop = new SceneObjectNode(troopIcon, "TroopBuild");

                systemNode.AddNode(build); systemNode.AddNode(mission); systemNode.AddNode(ship); systemNode.AddNode(fac); systemNode.AddNode(troop);

                SceneGraphManager.AddObject(systemNode);

            }
            Tick.TickTimerFinished += new Tick.Fire(Tick_TickTimerFinished);
        }

        /// <summary>
        ///  Checks for intersection with SceneObjects and opens appropriate dialogs if found
        /// </summary>
        void HandleMouseInput(object sender, MouseEventArgs e)
        {
            int mouseX = e.Position.X;
            int mouseY = e.Position.Y;

            if (delta > 0.4)
                delta = 0;

            bool inWindow = false;
            foreach (var temp in InputManager.Manager.Controls)
            {
                if(temp.AbsoluteRect.Intersects(new Rectangle(mouseX, mouseY, 10, 10)))
                    inWindow = true;
            }

            if ((e.State.LeftButton == ButtonState.Pressed) && (delta > 0) && (delta < 0.4) && (!inWindow))
            {
                Vector3 nearsource = new Vector3((float)mouseX, (float)mouseY, 0f);
                Vector3 farsource = new Vector3((float)mouseX, (float)mouseY, 1f);
                Matrix world = Matrix.CreateTranslation(0, 0, 0);

                Vector3 nearPoint = EngineManager.Device.Viewport.Unproject(nearsource, CameraManager.ActiveCamera.Projection, CameraManager.ActiveCamera.View, world);
                Vector3 farPoint = EngineManager.Device.Viewport.Unproject(farsource, CameraManager.ActiveCamera.Projection, CameraManager.ActiveCamera.View, world);

                Vector3 direction = farPoint - nearPoint;
                direction.Normalize();
                Ray pickRay = new Ray(nearPoint, direction);

                foreach (SceneObjectNode temp in SceneGraphManager.Root.Nodes)
                {

                    foreach (SceneObjectNode temp2 in temp.Nodes)
                    {
                        temp2.SceneObject.MeasureModel();
                        float? lol = pickRay.Intersects(temp2.SceneObject.BoundingBox);

                        if (lol.HasValue)
                        {
                            foreach (var system in NetClientManager.gameUniverse.dUniverse)
                            {
                                #region Check which Window to Show
                                if (temp.SceneObject.Name.Contains(system.Value.sName))
                                {
                                    if ((temp2.SceneObject.Name.Contains("MainBuild") && temp2.SceneObject.ReadyToRender == true))
                                    {
                                        bool found = false;
                                        foreach (var control in InputManager.Manager.Controls)
                                        {
                                            if (control.Name == system.Value.sName + " Main Dialog")
                                                found = true;
                                        }
                                        if (!found)
                                        {
                                            BuildWindow newBuildWindow = new BuildWindow(system.Value);
                                        }
                                    }
                                    if ((temp2.SceneObject.Name.Contains("Mission") && temp2.SceneObject.ReadyToRender == true))
                                    {
                                        bool found = false;
                                        foreach (var control in InputManager.Manager.Controls)
                                        {
                                            if (control.Name == system.Value.sName + " Mission Dialog")
                                                found = true;
                                        }
                                        if (!found)
                                        {
                                            BuildPopup newMissionWindow = new BuildPopup(system.Value, "Ship");
                                        } 
                                    }
                                    if (temp2.SceneObject.Name.Contains("Fleet") && temp2.SceneObject.ReadyToRender == true)
                                    {
                                        bool found = false;
                                        foreach (var control in InputManager.Manager.Controls)
                                        {
                                            if (control.Name == system.Value.sName + " Fleet Dialog")
                                                found = true;
                                        }
                                        if (!found)
                                        {
                                            FleetWindow newFleetWindow = new FleetWindow();
                                        }
                                    }
                                    if (temp2.SceneObject.Name.Contains("ShipBuild") && temp2.SceneObject.ReadyToRender == true)
                                    {
                                        bool found = false;
                                        foreach (var control in InputManager.Manager.Controls)
                                        {
                                            if ((control.Name == system.Value.sName + " Fighter Production Dialog") || (control.Name == system.Value.sName + " CapitalShip Production Dialog"))
                                                found = true;
                                        }
                                        if (!found)
                                        {
                                            ProductionWindow newFleetWindow = new ProductionWindow(NetClientManager.GetAvailableUnits("Ship"), system.Value);
                                        }
                                    }
                                    if (temp2.SceneObject.Name.Contains("FacBuild") && temp2.SceneObject.ReadyToRender == true)
                                    {
                                        bool found = false;
                                        foreach (var control in InputManager.Manager.Controls)
                                        {
                                            if (control.Name == system.Value.sName + " Facility Production Dialog")
                                                found = true;
                                        }
                                        if (!found)
                                        {
                                            ProductionWindow newFleetWindow = new ProductionWindow(NetClientManager.GetAvailableUnits("Facility"), system.Value);
                                        }
                                    }
                                    if (temp2.SceneObject.Name.Contains("TroopBuild") && temp2.SceneObject.ReadyToRender == true)
                                    {
                                        bool found = false;
                                        foreach (var control in InputManager.Manager.Controls)
                                        {
                                            if (control.Name == system.Value.sName + " Troop Production Dialog")
                                                found = true;
                                        }
                                        if (!found)
                                        {
                                            ProductionWindow newFleetWindow = new ProductionWindow(NetClientManager.GetAvailableUnits("Troop"), system.Value);
                                        }
                                    }
                                }
                                #endregion
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Used for checking Keyboard Input and Updating input accordingly
        /// </summary>
        void HandleInput(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Keys.Down:
                    CameraManager.ActiveCamera.Translate(new Vector3(0, -5, 0));
                    break;
                case Keys.S:
                    CameraManager.ActiveCamera.Translate(new Vector3(0, -5, 0));
                    break;
                case Keys.Up:
                    CameraManager.ActiveCamera.Translate(new Vector3(0, 5, 0));
                    break;
                case Keys.W:
                    CameraManager.ActiveCamera.Translate(new Vector3(0, 5, 0));
                    break;
                case Keys.Left:
                    CameraManager.ActiveCamera.Translate(new Vector3(-5, 0, 0));
                    break;
                case Keys.A:
                    CameraManager.ActiveCamera.Translate(new Vector3(-5, 0, 0));
                    break;
                case Keys.Right:
                    CameraManager.ActiveCamera.Translate(new Vector3(5, 0, 0));
                    break;
                case Keys.D:
                    CameraManager.ActiveCamera.Translate(new Vector3(5, 0, 0));
                    break;
                case Keys.PageUp:
                    CameraManager.ActiveCamera.Translate(new Vector3(0, 0, 5));
                    break;
                case Keys.PageDown:
                    CameraManager.ActiveCamera.Translate(new Vector3(0, 0, -5));
                    break;
                case Keys.Home:
                    CameraManager.ActiveCamera.Position = new Vector3(450, -350, 280);
                    break;
                case Keys.Escape:
                    EngineManager.Game.Exit();
                    break;
            }
        }

        void Tick_TickTimerFinished()
        {
            foreach (var temp in InputManager.Manager.Controls)
            {
                if (temp is BuildWindow)
                    (temp as BuildWindow).RefreshData();
            }
        }
        public override void UnloadContent()
        {
            base.UnloadContent();
        }

        /// <summary>
        /// Updates the Camera, the time changed and the message icons.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, false);
            delta += (float)gameTime.ElapsedGameTime.TotalSeconds;
            CameraManager.ActiveCamera.Update();

            #region Check MouseScroll
            currentState = Mouse.GetState();

            if(currentState.ScrollWheelValue < currentZ)
                if (CameraManager.ActiveCamera.Position.Z < 1500)
                    CameraManager.ActiveCamera.Translate(new Vector3(0, 0, 3.0f));

            if (currentState.ScrollWheelValue > currentZ)
                if (CameraManager.ActiveCamera.Position.Z > 200)
                    CameraManager.ActiveCamera.Translate(new Vector3(0, 0, -3.0f));

            currentZ = currentState.ScrollWheelValue;


            if (currentState.Y < 0.05 * EngineManager.Height)
                CameraManager.ActiveCamera.Translate(new Vector3(0, 0.5f, 0));
            if (currentState.Y > 0.95 * EngineManager.Height)
                CameraManager.ActiveCamera.Translate(new Vector3(0, -0.5f, 0));
            if (currentState.X < 0.05 * EngineManager.Width)
                CameraManager.ActiveCamera.Translate(new Vector3(- 0.5f, 0, 0));
            if (currentState.X > 0.95 * EngineManager.Width)
                CameraManager.ActiveCamera.Translate(new Vector3(0.5f, 0, 0));
            #endregion 
            #region MessageUpdates
            bool noneToRead = true;
            if (NetClientManager.MessageManager.ChatList.Count == 0)
                chatIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.ChatList)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    chatIcon.Color = Color.White;
                else
                    chatIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            }

            noneToRead = true;
            if (NetClientManager.MessageManager.ConflictList.Count == 0)
                conflictIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.ConflictList)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    conflictIcon.Color = Color.White;
                else
                    conflictIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            }

            noneToRead = true;
            if (NetClientManager.MessageManager.DefenceList.Count == 0)
                defenceIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.DefenceList)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    defenceIcon.Color = Color.White;
                else
                    defenceIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            }

            noneToRead = true;
            if (NetClientManager.MessageManager.FleetList.Count == 0)
                fleetIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.FleetList)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    fleetIcon.Color = Color.White;
                else
                    fleetIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            }

            noneToRead = true;
            if (NetClientManager.MessageManager.ManufactureList.Count == 0)
                manufactureIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.ManufactureList)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    manufactureIcon.Color = Color.White;
                else
                    manufactureIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            }

            noneToRead = true;
            if (NetClientManager.MessageManager.MissionList.Count == 0)
                missionIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.MissionList)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    missionIcon.Color = Color.White;
                else
                    missionIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            }

            noneToRead = true;
            if (NetClientManager.MessageManager.PopularSupport.Count == 0)
                popularSupport.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.PopularSupport)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    popularSupport.Color = Color.White;
                else
                    popularSupport.Color = new Color(0.5f, 0.5f, 0.5f);
            }

            noneToRead = true;
            if (NetClientManager.MessageManager.ResourceList.Count == 0)
                resourceIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            else
            {
                foreach (var message in NetClientManager.MessageManager.ResourceList)
                {
                    if (message.IsRead)
                        noneToRead = false;
                }
                if (noneToRead)
                    resourceIcon.Color = Color.White;
                else
                    resourceIcon.Color = new Color(0.5f, 0.5f, 0.5f);
            }
            #endregion
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
            
            byte fade = TransitionAlpha;

            float time = (float)gameTime.TotalGameTime.TotalSeconds;

            // Create a new Effect from planet. Set the properties and prepare to draw planets
            Effect effect = ShaderManager.GetShader("Planet");
            effect.Parameters["View"].SetValue(CameraManager.ActiveCamera.View);
            effect.Parameters["Projection"].SetValue(CameraManager.ActiveCamera.Projection);
            effect.Parameters["CameraPosition"].SetValue(CameraManager.ActiveCamera.Position);
            effect.Parameters["Time"].SetValue(time);

            ScreenManager.SpriteBatch.Begin();
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("starBackground").BaseTexture as Texture2D, new Rectangle(-500, -500, EngineManager.Width + 500, EngineManager.Height + 500), Color.AntiqueWhite);
            
            
            foreach(var system in NetClientManager.gameUniverse.dUniverse)
            {
                Vector3 stringProject = EngineManager.Device.Viewport.Project(new Vector3(system.Value.vPosition.X, system.Value.vPosition.Y - 10, 0), CameraManager.ActiveCamera.Projection, CameraManager.ActiveCamera.View, Matrix.Identity);
                    
                if (CameraManager.ActiveCamera.Position.Z < 500)
                {
                    #region Draw Planet Diplomacy
                    Vector3 diplomacyProjectstart = EngineManager.Device.Viewport.Project(new Vector3(system.Value.vPosition.X - 6, system.Value.vPosition.Y - 7, 0), CameraManager.ActiveCamera.Projection, CameraManager.ActiveCamera.View, Matrix.Identity);
                    Vector3 diplomacyProjectend = EngineManager.Device.Viewport.Project(new Vector3(system.Value.vPosition.X + 6, system.Value.vPosition.Y - 8, 0), CameraManager.ActiveCamera.Projection, CameraManager.ActiveCamera.View, Matrix.Identity);

                    if (((diplomacyProjectend.X > 0) && (diplomacyProjectstart.X < EngineManager.Width)) && ((diplomacyProjectend.Y > 0) && (diplomacyProjectstart.Y < EngineManager.Height)))
                    {
                        float empwidth = (diplomacyProjectend.X - diplomacyProjectstart.X) * ((float)system.Value.iLoyaltyEmpire / 100);
                        float neutwidth = (diplomacyProjectend.X - diplomacyProjectstart.X) * ((float)system.Value.iLoyaltySystem / 100);
                        float rebwidth = (diplomacyProjectend.X - diplomacyProjectstart.X) * ((float)system.Value.iLoyaltyAlliance / 100);
                        float height = (diplomacyProjectend.Y - diplomacyProjectstart.Y);

                        Rectangle empireRectangle = new Rectangle((int)(diplomacyProjectstart.X), (int)diplomacyProjectstart.Y, (int)empwidth, (int)height);
                        Rectangle neutralRectangle = new Rectangle((int)(diplomacyProjectstart.X + empwidth), (int)diplomacyProjectstart.Y, (int)neutwidth, (int)height);
                        Rectangle allianceRectangle = new Rectangle((int)(diplomacyProjectstart.X + empwidth + neutwidth), (int)diplomacyProjectstart.Y, (int)rebwidth, (int)height);

                        ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, empireRectangle, Color.Green);
                        ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, neutralRectangle, Color.Turquoise);
                        ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("blank").BaseTexture as Texture2D, allianceRectangle, Color.Red);
                    }
                }
                #endregion
               /*
                #region Horrible Horrible Solution to checking if Fleet or Mission is empty and not drawing
               if (system.Value.lFleet.Count == 0)
                {
                    foreach (var temp in SceneGraphManager.Root.Nodes)
                    {
                        if (temp.key == system.Value.sName)
                        {
                            foreach (var temp2 in temp.Nodes)
                            {
                                if (temp2.key == "fleet")
                                {
                                    ((SceneObjectNode)temp2).SceneObject.ReadyToRender = false;
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (var temp in SceneGraphManager.Root.Nodes)
                    {
                        if (temp.key == system.Value.sName)
                        {
                            foreach (var temp2 in temp.Nodes)
                            {
                                if (temp2.key == "fleet")
                                {
                                    ((SceneObjectNode)temp2).SceneObject.ReadyToRender = true;
                                }
                            }
                        }
                    }
                }

                if (system.Value.lMission.Count == 0)
                {
                    foreach (var temp in SceneGraphManager.Root.Nodes)
                    {
                        if (temp.key == system.Value.sName)
                        {
                            foreach (var temp2 in temp.Nodes)
                            {
                                if (temp2.key == "mission")
                                {
                                    ((SceneObjectNode)temp2).SceneObject.ReadyToRender = false;
                                }
                            }
                        }
                    }
                }
                else
                {
                    foreach (var temp in SceneGraphManager.Root.Nodes)
                    {
                        if (temp.key == system.Value.sName)
                        {
                            foreach (var temp2 in temp.Nodes)
                            {
                                if (temp2.key == "mission")
                                {
                                    ((SceneObjectNode)temp2).SceneObject.ReadyToRender = true;
                                }
                            }
                        }
                    }
                }
                #endregion
                */
                float x = ScreenManager.Font.MeasureString(system.Value.sName).X / 4;
                ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, system.Value.sName, new Vector2(stringProject.X - x, stringProject.Y), system.Value.TeamColor, 0, Vector2.One, 0.5f, SpriteEffects.None, 1);
            }             
            
            // Draw the FPS and current GameTurn.
            ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, NetClientManager.GameTurn.ToString(), new Vector2(EngineManager.Width - 60, 60), Color.White);
            ScreenManager.SpriteBatch.DrawString(ScreenManager.Font, FpsCounter.FPS.ToString(), new Vector2(EngineManager.Width - 60, 20), Color.White);
            ScreenManager.SpriteBatch.End();

            #region Drawing Lines
            basicEffect.View = CameraManager.ActiveCamera.View;
            basicEffect.World = Matrix.Identity;
            basicEffect.Projection = CameraManager.ActiveCamera.Projection;
            

            foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                
                if (lineListIndicies.Count > 0)
                    EngineManager.Device.DrawUserIndexedPrimitives<VertexPositionColor>(
                    PrimitiveType.LineList,
                    pointList.ToArray(),
                    0,  // vertex buffer offset to add to each element of the index buffer
                    NetClientManager.gameUniverse.dUniverse.Count,  // number of vertices in pointList
                    lineListIndicies.ToArray(),  // the index buffer
                    0,  // first index element to read
                    (lineListIndicies.Count / 2)   // number of primitives to draw
                    );
            }
            #endregion

            // Used to draw all the planets and icons added to the scenegraph manager
            SceneGraphManager.Draw(gameTime);

            
            //Finally draw the GUI
            ScreenManager.SpriteBatch.Begin();
            ScreenManager.SpriteBatch.Draw(TextureManager.GetTexture("Gui").BaseTexture as Texture2D, EngineManager.Device.Viewport.Bounds, Color.White);
            ScreenManager.SpriteBatch.End();
        }
    }
}
